var toast = require("../../../components/toast/toast.js")
var common = require('../../../utils/util.js')
var app = getApp();

Page({
  data: {
	  imgUrls: '',
	  isShowImg: false,

    NotHasCarList: "hide",
    HasCarList: "hide",
    indicatorDots: false,
    autoplay: false,
    interval: 3000,
    duration: 1000,
    list: [],
    isShowFootNav: true,
    num: 0
  },
  //底部切换页面方法
	toUrl:function (e) {
    var url = e.currentTarget.dataset.url;
    console.log( app.globalData.appid)
		if(url!='/pages/carInfo/list/list'){
			if(url == ''){
				//develop（开发版），trial（体验版），release（正式版）
				var res = {
					appid: app.globalData.appid,
					path: '',
					envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			}else {
			  app.redirectTo({url: url})
			}
		}
	},
  widgetsToggle: function (e) {
    var carId = e.currentTarget.dataset.carid;
    var voliationCount = e.currentTarget.dataset.voliationcount;
    var fineTotalAmount = e.currentTarget.dataset.finetotalamount;
    var degreeCount = e.currentTarget.dataset.degreecount;
    var carNumber = e.currentTarget.dataset.carnumber;
    wx.navigateTo({
      url: '../illegal/illegal?carId=' + carId + '&carNumber=' + carNumber + '&voliationCount=' + voliationCount + '&fineTotalAmount=' + fineTotalAmount + '&degreeCount=' + degreeCount
    })
  },

  carAdd: function (e) {
    var tsPage = this;
    var carList = this.data.list;

    if (carList.length < 3) {   // 最多显示3辆车
      wx.navigateTo({
        url: '../edit/edit'
      })
    }
    else {
      toast.show(tsPage, "您最多只能添加3辆车");
    }

  },
  GetCarList: function (e) {
    var param = {
      url: '/wx/carViola/selectCars.ajax'
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行

      },
      success: data => {
        if (data.successFlag) {
          var carList = data.data;
          carList.map(item => {
            let carNum = item.carNumber.substring(0, 3) + (item.carNumber.length == 7 ? '**' : '***') + item.carNumber.substring(item.carNumber.length - 2, item.carNumber.length);
            item.carNumberOmit = carNum;
          });
          this.setData({
            "list": carList
          })
          if (carList.length > 0) {
            this.setData({
              "HasCarList": "",
              "NotHasCarList": "hide"
            })
          }
          else {
            this.setData({
              "HasCarList": "hide",
              "NotHasCarList": ""
            })
          }
          //异步刷新违章
          this.RefreshCarInfo(carList);
        } else {
          toast.show(this, data.errormsg)
        }
      },
      complete: data => {
        // wx.hideToast();
      }
    });
  },
  RefreshCarInfo: function (carList) {
    var newCarList = [];
    this.Recursion(carList, 0);
    this.setData({
      "list": carList
    })
  },
  Recursion: function (carList, index) {
    //因为微信限制并发5个请求，所以这里需要一条一条的刷新违章

    if (index >= carList.length) {
      this.setData({
        "list": carList
      })
      return;
    }

    var item = carList[index];
    var param = {
      url: '/wx/carViola/selectCarInfo.ajax',
      para: { "carId": item.carId, "isGet": 1 }
    };

    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
      },
      success: data => {
        if (data.successFlag) {
          item.voliationCount = data.data.voliationCount;
          item.fineTotalAmount = data.data.fineTotalAmount;
          item.degreeCount = data.data.degreeCount;
        } else {
          console.error(data);
        }
        this.Recursion(carList, ++index);
      },
      complete: data => {
        // wx.hideToast();
      }
    });
  },
  //获得广告图片
  getAdvertisement: function () {
    var that = this;
	  var param = {
		  url: '/wx/carViola/ad.ajax',
		  para: {}
	  };
	  app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
		  },
		  success: data => {
        var imgUrls = data.body;
        if(imgUrls!=null){
          that.setData({
	          imgUrls: imgUrls.icon,
            isShowImg: true
          })
        }else {
	        that.setData({
		        imgUrls: imgUrls.icon,
		        isShowImg: false
	        })
        }
	    },
      complete: data => {
        // wx.hideToast();
      }
     });
  },

  onLoad: function (options) {
      // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
      app.globalData.channelId = decodeURIComponent(options.scene)=='undefined'?'':decodeURIComponent(options.scene);
      console.log("channelId",app.globalData.channelId);
    this.setData({
      "HasCarList": "hide",
      "NotHasCarList": "hide"
    })
    wx.showToast({
      title: '请稍候',
      icon: 'loading',
      duration: 10000,
      mask: true
    });

    this.getAdvertisement()
  },
  onShow: function () {
    // 获取车辆列表
    this.GetCarList();

  },

  onReady: function () {
    // 页面渲染完成
    wx.hideToast();
  },
  onShareAppMessage: function () {
    return {
      title: '还在为违章处理排队烦恼吗？',
      desc: '邮证查办违章，免费查询，实时提醒，快速在线缴罚款，车主最贴心的车务管家！ ',
      path: 'pages/carInfo/list/list'
    }
  }
})